package cn.pn.project.service;

import cn.pn.project.common.Page;

import cn.pn.project.mapper.comment.CommentMapper;
import cn.pn.project.mapper.comment.LikeMapper;
import cn.pn.project.pojo.comment.Comment;
import cn.pn.project.pojo.comment.Like;
import cn.pn.project.pojo.commodity.Commodity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/comment")
public class CommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private LikeMapper likeMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 根据评论id查询评论
     * @param commentId
     * @return
     */
    @RequestMapping("/commentById")
    public Comment getCommentByCommentId(@Param("commentId") Integer commentId) throws Exception {
        return commentMapper.getCommentByCommentId(commentId);
    }
    /**
     * 根据商品id查询该商品的主评论集合
     * @param commodityId 商品id
     * @return 主评论集合
     * @throws Exception
     */
    @RequestMapping("/listMain")
    public Page<Comment> listMainComment(
            @RequestParam("commodityId") Integer commodityId,
            @RequestParam("pageNo")Integer pageNo,
            @RequestParam("pageSize")Integer pageSize) throws Exception{
        System.out.println("-----------provider的/comment/listMain方法，执行查找主评论集合-----------");
        Page<Comment> page=null;
        String key="mainComment"+commodityId+"Page"+pageNo;
        //操作redis的值的对象
        ValueOperations<String,Page<Comment>> operations = redisTemplate.opsForValue();
        boolean hasKey = redisTemplate.hasKey(key);
        if(hasKey){
            System.out.println("从缓存中拿取"+key+"的数据>>>>>>>>>>>>>>>>");
            page=operations.get(key);
        }else{
            System.out.println("从数据库中拿取数据>>>>>>>>>>>>>>>>");
            page=new Page<Comment>(pageNo,pageSize,commentMapper.mainCountByCommodityId(commodityId));
            page.setRows(commentMapper.listMainComment(commodityId,page));
            System.out.println("当前页数："+page.getCurPage()+",起始下标："+page.getBeginPos()+",页大小："+page.getPageSize()+",总记录数："+page.getTotal()+",总页数："+page.getPageCount()+",集合记录数："+page.getRows().size());
            //操作ValueOperation对象，将键和查询到的数据一起放入缓存
            operations.set(key,page,30, TimeUnit.MINUTES);
        }
        return page;
    }

    /**
     * 根据商品id查询主评论条数
     * @param commodityId 商品id
     * @return
     * @throws Exception
     */
    @RequestMapping("/mainCommentCount")
    public Integer mainCountByCommodityId(@RequestParam("commodityId") Integer commodityId) throws Exception {
        return commentMapper.mainCountByCommodityId(commodityId);
    }
    /**
     * 根据商品id查询该商品的主评论的子评论
     * @param commodityId 商品id
     * @return 某主评论的子评论的集合
     * @throws Exception
     */
    @RequestMapping("/listChild")
    public Page<Comment> listChildComment(
            @RequestParam("belongToId") Integer belongToId
            ,@RequestParam("commodityId") Integer commodityId
            ,@RequestParam("pageNo")Integer pageNo
            ,@RequestParam("pageSize")Integer pageSize) throws Exception{
        System.out.println("-----------provider的/comment/listMain方法，执行查找某主评论的子评论集合-----------");
        Page<Comment> page=null;
        //固定前缀childComment+商品id+所属主评论id+当前页数
        String key="childComment"+commodityId+"Are"+belongToId+"Page"+pageNo;
        ValueOperations<String,Page> operations =redisTemplate.opsForValue();
        boolean hasKey=redisTemplate.hasKey(key);
        if(hasKey){
            System.out.println("从缓存中拿取"+key+"的数据>>>>>>>>>>>>>>>>");
            page=operations.get(key);
        }else{
            page=new Page<Comment>(pageNo,pageSize,commentMapper.childCommentCount(belongToId,commodityId));
            page.setRows(commentMapper.listChildComment(belongToId,commodityId,page));
            //操作ValueOperation对象，将键和查询到的数据一起放入缓存
            operations.set(key,page,30,TimeUnit.MINUTES);
        }

        return page;
    }

    /**
     * 根据用户id和商品id查询当前用户是否评论当前商品
     * @param userId 用户id
     * @param commodityId 商品id
     * @return 评论对象/null
     * @throws Exception
     */
    @RequestMapping("/isCommentedOn")
    public Comment isCommentedOn(@RequestParam("userId") Integer userId,@RequestParam("commodityId")Integer commodityId) throws Exception{
        return commentMapper.isCommentedOn(userId,commodityId);
    }

    /**
     * 添加主评论
     * @param comment 评论对象
     * @return 新评论对象/null
     * @throws Exception
     */
    @RequestMapping("/addMain")
    public Comment addMainComment(@RequestBody Comment comment) throws Exception{
        comment.setCommentTime(new Date());//当前时间
        //先删除缓存再操作数据
        for (int i=1;i<6;i++){//条件可以改为 i<符合条件的记录数/10
            String key1="mainComment"+comment.getCommodityId()+"Page"+i;
            boolean has=redisTemplate.hasKey(key1);
            if(has){
                System.out.println(">>>>>>>>>>>>删除："+key1);
                redisTemplate.delete(key1);
            }
        }
        Comment commentBack=null;
        int result = commentMapper.addComment(comment);
        if(result>0){//新增成功后查找并返回对象
            System.out.println("主评论新增结果："+result);
            commentBack=commentMapper.isCommentedOn(comment.getUserId(),comment.getCommodityId());
        }
        return commentBack;
    }

    /**
     * 添加子评论
     * @param comment 评论对象
     * @return 0 1
     * @throws Exception
     */
    @Transactional(propagation= Propagation.SUPPORTS,readOnly=true)
    @RequestMapping("/addChild")
    public Integer addChildComment(@RequestBody Comment comment) throws Exception{
        System.out.println(comment.getContent()+"---------------"+comment.getBelongToId());
        int result=0;
        comment.setCommentTime(new Date());//当前时间
        //先删除缓存再操作数据
        for (int i=1;i<6;i++){
            String key1="childComment"+comment.getCommodityId()+"Are"+comment.getBelongToId()+"Page"+i;
            boolean has=redisTemplate.hasKey(key1);
            if(has){
                System.out.println(">>>>>>>>>>>>删除："+key1);
                redisTemplate.delete(key1);
            }
        }
        int jie1=commentMapper.addComment(comment);//新增一条回复
        int jie2=commentMapper.childCountRise(comment.getBelongToId());//修改主评论回复数
        if(jie1>0&&jie2>0){
            result=1;
        }
        System.out.println("新增总结果："+result);
        return result;
    }

    /**
     * 修改主评论
     * @param comment 评论对象
     * @return 修改后对象/null
     * @throws Exception
     */
    @RequestMapping("/updateComment")
    public Comment updateComment(@RequestParam("comment") Comment comment) throws Exception{
        Comment commentBack=null;
        //先删除缓存再操作数据
        for (int i=1;i<6;i++){//条件可以改为 i<符合条件的记录数/10
            String key1="mainComment"+comment.getCommodityId()+"Page"+i;
            boolean has=redisTemplate.hasKey(key1);
            if(has){
                redisTemplate.delete(key1);//删除key1
            }
        }
        int result = commentMapper.updateComment(comment);
        if(result>0){//修改成功后查找并返回对象
            System.out.println("主评论修改结果："+result);
            commentBack=commentMapper.isCommentedOn(comment.getUserId(),comment.getCommodityId());
        }
        return commentBack;
    }

    /**
     * 该用户该评论是否点赞
     * @param like
     * @return 0 1
     * @throws Exception
     */
    @RequestMapping("/isLikedOn")
    public Integer isLikedOn(@RequestParam("like") Like like) throws Exception{
        return likeMapper.isLiked(like);
    }

    /**
     * 点赞
     * @param like
     * @return 0 1
     * @throws Exception
     */
    @Transactional(propagation= Propagation.SUPPORTS,readOnly=true)
    @RequestMapping("/addLike")
    public Integer addLike(@RequestParam("like") Like like) throws Exception{
        int result=0;
        int jie1=likeMapper.addLike(like);
        int jie2=commentMapper.likeCountRise(like.getCommentId());
        if(jie1>0&jie2>0){
            result=1;
        }
        return result;
    }

    /**
     * 取消点赞
     * @param like
     * @return 0 1
     * @throws Exception
     */
    @RequestMapping("/delLike")
    @Transactional(propagation= Propagation.SUPPORTS,readOnly=true)
    public Integer delLike(@RequestParam("like") Like like) throws Exception{
        int result=0;
        int jie1=likeMapper.delLike(like);
        int jie2=commentMapper.likeCountDown(like.getCommentId());
        if(jie1>0&jie2>0){
            result=1;
        }
        return result;
    }

}
